package com.github.postsanf.yinian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.ContactGroupUserAdapter2;
import com.github.postsanf.yinian.bean.YNContactUser;
import com.github.postsanf.yinian.utils.CharacterParser;
import com.github.postsanf.yinian.utils.GetContactUser;
import com.github.postsanf.yinian.utils.PinyinComparator;
import com.github.postsanf.yinian.widget.Sidebar;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class AitePhoneSelectActivity extends BaseActivity implements View.OnClickListener {
    private ListView sortListView;
    //    private EditText searchEditText;
    private ContactGroupUserAdapter2 contactUserAdapter;
    private LinearLayout titleLayout;
    private TextView title;
    private TextView tvNofriends;
    // 滚动记录标识
    private int lastFirstVisibleItem = -1;
    // 汉字转拼音
    private CharacterParser characterParser;
    private List<YNContactUser> SourceDateList;
    // 根据拼音排表
    private PinyinComparator pinyinComparator;
    private Sidebar sidebar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_aitephone_select);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        initView();
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        findViewById(R.id.tv_complete).setOnClickListener(this);
        GetContactUser.GetContactUser(this);
        titleLayout = (LinearLayout) findViewById(R.id.title_layout);
        title = (TextView) this.findViewById(R.id.title_layout_catalog);
        tvNofriends = (TextView) this.findViewById(R.id.title_layout_no_friends);
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();
        sortListView = (ListView) findViewById(R.id.lv_contact_user_list);
        sidebar = (Sidebar) findViewById(R.id.sidebar);
        sidebar.setListView(sortListView);
        sortListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 取得ViewHolder对象，这样就省去了通过层层的findViewById去实例化我们需要的item_cb实例的步骤
                ContactGroupUserAdapter2.ViewHolder holder = (ContactGroupUserAdapter2.ViewHolder) view.getTag();
                // 改变CheckBox的状态
                holder.item_cb.toggle();
                // 将CheckBox的选中状况记录下来
                contactUserAdapter.getIsSelected().put(Integer.parseInt(holder.setposition.getText().toString()), holder.item_cb.isChecked());
            }
        });
        SourceDateList = filledData(GetContactUser.lists);
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        contactUserAdapter = new ContactGroupUserAdapter2(SourceDateList, this);
        sortListView.setAdapter(contactUserAdapter);
//        sortListView.setOnScrollListener(new AbsListView.OnScrollListener() {
//            @Override
//            public void onScrollStateChanged(AbsListView view, int scrollState) {
//            }
//
//            @Override
//            public void onScroll(AbsListView view, int firstVisibleItem,
//                                 int visibleItemCount, int totalItemCount) {
//                if (SourceDateList.size() <= 0) {
//                    return;
//                }
//                int section = getSectionForPosition(firstVisibleItem);
//                int nextSection = getSectionForPosition(firstVisibleItem + 1);
//                int nextSecPosition = getPositionForSection(+nextSection);
//                if (firstVisibleItem != lastFirstVisibleItem) {
//                    ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
//                            .getLayoutParams();
//                    params.topMargin = 0;
//                    titleLayout.setLayoutParams(params);
//                    title.setText(SourceDateList.get(
//                            getPositionForSection(section)).getNameLetters());
//                }
//                if (nextSecPosition == firstVisibleItem + 1) {
//                    View childView = view.getChildAt(0);
//                    if (childView != null) {
//                        int titleHeight = titleLayout.getHeight();
//                        int bottom = childView.getBottom();
//                        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) titleLayout
//                                .getLayoutParams();
//                        if (bottom < titleHeight) {
//                            float pushedDistance = bottom - titleHeight;
//                            params.topMargin = (int) pushedDistance;
//                            titleLayout.setLayoutParams(params);
//                        } else {
//                            if (params.topMargin != 0) {
//                                params.topMargin = 0;
//                                titleLayout.setLayoutParams(params);
//                            }
//                        }
//                    }
//                }
//                lastFirstVisibleItem = firstVisibleItem;
//            }
//        });

//        searchEditText = (EditText) findViewById(R.id.et_serch_text);
        // 根据输入框输入值的改变来过滤搜索
//        searchEditText.addTextChangedListener(new TextWatcher() {
//            @Override
//            public void onTextChanged(CharSequence s, int start, int before,
//                                      int count) {
//                // 这个时候不需要挤压效果 就把他隐藏掉
//                titleLayout.setVisibility(View.GONE);
//                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
//                filterData(s.toString());
//            }
//
//            @Override
//            public void beforeTextChanged(CharSequence s, int start, int count,
//                                          int after) {
//            }
//
//            @Override
//            public void afterTextChanged(Editable s) {
//            }
//        });
    }


    // 增加分类并为ListView填充数据
    private List<YNContactUser> filledData(List<YNContactUser> datas) {
        for (int i = 0; i < datas.size(); i++) {
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(datas.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();
            if (sortString.matches("[A-Z]")) {
                datas.get(i).setNameLetters(sortString.toUpperCase());
            } else {
                datas.get(i).setNameLetters("#");
            }
        }
        return datas;
    }

    // 根据输入数据过滤并更新ListView
    private void filterData(String filterStr) {
        List<YNContactUser> filterDateList = new ArrayList<YNContactUser>();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
            tvNofriends.setVisibility(View.GONE);
        } else {
            filterDateList.clear();
            for (YNContactUser sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1
                        || characterParser.getSelling(name).startsWith(
                        filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }
        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        contactUserAdapter.updateListView(filterDateList);
        if (filterDateList.size() == 0) {
            tvNofriends.setVisibility(View.VISIBLE);
        }
    }

//    @Override
//    public Object[] getSections() {
//        return null;
//    }

    //  根据ListView的当前位置获取分类的首字母的Char ascii值
//    public int getSectionForPosition(int position) {
//        if (SourceDateList.size() <= 0) {
//            finish();
//            return 0;
//        }
//        if (position < SourceDateList.size()) {
//            return SourceDateList.get(position).getNameLetters().charAt(0);
//        }
//        return 0;
//    }
//
//    //  根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
//    public int getPositionForSection(int section) {
//        for (int i = 0; i < SourceDateList.size(); i++) {
//            String sortStr = SourceDateList.get(i).getNameLetters();
//            char firstChar = sortStr.toUpperCase().charAt(0);
//            if (firstChar == section) {
//                return i;
//            }
//        }
//        return -1;
//    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_complete:
                HashMap<Integer, Boolean> invateYes = contactUserAdapter.getIsSelected();
                if (invateYes.size() == 0) {
                    Toast.makeText(this, "未选择联系人", Toast.LENGTH_SHORT).show();
                    return;
                }
                for (int i = 0; i < invateYes.size(); i++) {
                    if (invateYes.get(i)) {
                        for (int j = 0; j < SourceDateList.size(); j++) {
                            if (SourceDateList.get(j).getId() == i) {
                                String tempName = SourceDateList.get(j).getName();
                                Intent pintent = new Intent("updatephonetag");
                                pintent.putExtra("phonename", tempName);
                                sendBroadcast(pintent);
                            }
                        }
                    }
                }
                finish();
                break;
            default:
                break;
        }
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }


}
